<!--
 * @FilePath: /my-map-demo/src/views/spatial-analysis/MapBase.vue
 * @Author: 张文鑫
 * @Date: 2024-12-26 17:09:37
 * @Description: 
-->
<template>
  <div class="map-container">
    <div class="map-content">
      <!-- Loading 指示器 -->
      <div v-if="loading" class="loading-overlay">加载中...</div>
      <div id="map"></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount } from "vue";
import "ol/ol.css";
import { Map, View } from "ol";
import { districtLayer } from "./config/index.js";
import { ref, provide } from "vue";
const props = defineProps({
  layers: {
    type: Array, // 动态传入图层
  },
});
let map = null;
const loading = ref(false);
// 向外触发事件，通知父组件地图实例
const emit = defineEmits(["map-initialized"]);
onMounted(() => {
  loading.value = true;
  // 创建地图实例 图层顺序很重要！！！！！！！！！
  map = new Map({
    target: "map", // 将地图渲染到容器中
    layers: [districtLayer, ...props.layers],
    view: new View({
      center: [119.45, 29.85], // 杭州市的中心点
      zoom: 8,
      projection: "EPSG:4326",
    }),
  });

  // 确保在地图创建后再提供实例
  provide("map", map);

  map.on("rendercomplete", () => {
    loading.value = false;
  });

  emit("map-initialized", map);
});

onBeforeUnmount(() => {
  if (map) map.setTarget(null);
});
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  .map-content {
    z-index: 0;
    #map {
      height: 90vh;
      z-index: 1;
      border: none;
      cursor: move;
      background: #000;
    }
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    color: #333;
    z-index: 99; /* 保证 loading 层在地图上层 */
  }
}
</style>
